import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, Drawer, message, Modal, Popover, Tag } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import AccountRoleDetail from './components/AccountRoleDetail';
import AddFrom from './components/AddForm';
import type { AuthRoleAddItem, AuthRoleTableListItem } from './data';
import { addAdminRole, queryAdminRoleDetail, queryAdminRoleList, removeAdminRole } from './service';
import EditForm from '@/pages/Auth/AuthRole/components/EditForm';

const TableList: React.FC = () => {
    const [sorter, setSorter] = useState<string>('');
    const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
    const [detailVisible, setDetailVisible] = useState<boolean>(false);
    const [editVisible, setEditVisible] = useState<boolean>(false);
    const [clickItemId, setClickItemId] = useState<string>('');
    const [clickItem, setClickItem] = useState<AuthRoleTableListItem>();
    const actionRef = useRef<ActionType>();

    async function handleAdd(fields: AuthRoleAddItem) {
        const hide = message.loading('正在添加');
        try {
            const res = await addAdminRole(fields);
            hide();
            if (res.code == 0) {
                message.success('添加成功');
                actionRef.current?.reload();
                handleAddModalVisible(false);
                return true;
            } else {
                message.error(`${res.message}`);
                return false;
            }
        } catch (error) {
            hide();
            message.error('添加失败请重试！');
            handleAddModalVisible(false);
            return false;
        }
    }

    const handleRemove = async (fields: { id: string }) => {
        const hide = message.loading('正在删除');
        try {
            const res = await removeAdminRole(fields);
            hide();
            if (res.code == 0) {
                message.success('删除成功');
                actionRef.current?.reload();
                return true;
            } else {
                message.error(`${res.message}`);
                return false;
            }
        } catch (error) {
            hide();
            message.error('删除失败请重试！');
            return false;
        }
    };

    const columns: ProColumns<AuthRoleTableListItem>[] = [
        {
            title: '名称',
            dataIndex: 'name',
            ellipsis: true,
        },
        {
            title: '编号',
            dataIndex: 'id',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '权限',
            ellipsis: true,
            dataIndex: 'accesses',
            hideInSearch: true,
            render: (_, record) => {
                const { permissions } = record;
                if (!permissions) return null;
                const showAccesses = permissions.slice(0, 6);
                return (
                    // @ts-ignore
                    <Popover
                        placement="topLeft"
                        content={
                            <div style={{ maxWidth: 300 }}>
                                {permissions.map((item) => (
                                    <Tag style={{ margin: 2 }} key={item.id}>
                                        {item.name}
                                    </Tag>
                                ))}
                            </div>
                        }
                    >
                        {showAccesses.map((item) => (
                            <Tag key={item.id}>{item.name}</Tag>
                        ))}
                        {showAccesses.length < permissions.length ? '...' : ''}
                    </Popover>
                );
            },
        },
        {
            title: '操作',
            //@ts-ignore
            dataIndex: 'options',
            hideInSearch: true,
            ellipsis: true,
            render: (_, record) => {
                const onClickDetail = () => {
                    setDetailVisible(true);
                    setClickItemId(record.id);
                };

                const onClickRemove = () => {
                    const { id, name } = record;
                    Modal.confirm({
                        title: `删除角色 ${id}`,
                        content: (
                            <>
                                <Divider />
                                <p>确认要删除角色</p>
                                <span style={{ fontWeight: 'bolder' }}>{name}</span>&nbsp;&nbsp;?
                            </>
                        ),
                        okText: '确定',
                        cancelText: '取消',
                        onOk: async () => {
                            await handleRemove({ id });
                        },
                        centered: true,
                        width: '30vw',
                        style: { height: '18vw' },
                    });
                };

                return (
                    <div>
                        <a onClick={onClickDetail}>详情</a>
                        <Divider type="vertical" />
                        <a
                            onClick={() => {
                                setEditVisible(true);
                                setClickItem(record);
                            }}
                        >
                            修改
                        </a>
                        <Divider type="vertical" />
                        <a onClick={onClickRemove}>删除</a>
                    </div>
                );
            },
        },
    ];

    return (
        <PageHeaderWrapper>
            <ProTable<AuthRoleTableListItem>
                search={{
                    labelWidth: 'auto',
                    span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
                }}
                pagination={{
                    defaultPageSize: 10,
                    size: 'default',
                    showQuickJumper: true,
                    showSizeChanger: true,
                }}
                headerTitle="角色列表"
                actionRef={actionRef}
                rowKey="id"
                scroll={{ x: true }}
                onChange={(_, _filter, _sorter) => {
                    const sorterResult = _sorter as SorterResult<AuthRoleTableListItem>;
                    if (sorterResult.field) {
                        setSorter(`${sorterResult.field}_${sorterResult.order}`);
                    }
                }}
                params={{
                    sorter,
                }}
                toolBarRender={() => [
                    <Button type="primary" onClick={() => handleAddModalVisible(true)}>
                        <PlusOutlined /> 添加
                    </Button>,
                ]}
                tableAlertRender={() => false}
                rowSelection={false}
                request={(params = {}) => {
                    const { current: page, pageSize, ...filter } = params;
                    return queryAdminRoleList({ page, pageSize, ...filter });
                }}
                columns={columns}
            />
            <AddFrom
                modalVisible={addModalVisible}
                onVisibleChange={(visible) => handleAddModalVisible(visible)}
                onSubmit={async (value) => {
                    return await handleAdd(value);
                }}
            />

            {clickItem && editVisible && (
                <EditForm
                    item={clickItem}
                    modalVisible={editVisible}
                    onSubmit={() => {
                        setEditVisible(false);
                        setClickItem(undefined);
                        actionRef.current?.reload();
                    }}
                    onVisibleChange={(visible) => {
                        setEditVisible(visible);
                    }}
                />
            )}

            <Drawer
                visible={!!clickItemId && detailVisible}
                onClose={() => setDetailVisible(false)}
                width="325px"
            >
                {!!clickItemId && detailVisible && (
                    <AccountRoleDetail
                        id={clickItemId}
                        request={(id) => queryAdminRoleDetail({ id })}
                        reloadFunc={() => actionRef.current?.reload()}
                    />
                )}
            </Drawer>
        </PageHeaderWrapper>
    );
};

export default TableList;
